package com.github.livebase.database;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.github.livebase.log.Logger;
import com.github.livebase.log.LoggerFactory;

/**
 * @ClassName AppointmentOperator
 * @description: 预约的数据库操作
 * @author: biao532
 * @create: 2024-01-04 16:21
 * @Version 1.0
 **/
public class BookingOperator {
    public class Booking {
        private long time;
        private String type;
        private String message;
        private long i_time;

        public Booking(long time, String type, String message, long i_time) {
            this.time = time;
            this.type = type;
            this.message = message;
            this.i_time = i_time;
        }

        public long getI_time() {
            return i_time;
        }

        public long getTime() {
            return time;
        }

        public String getMessage() {
            return message;
        }

        public String getType() {
            return type;
        }

        @Override
        public String toString() {
            return "Booking{" +
                    "time=" + time +
                    ", type='" + type + '\'' +
                    ", message='" + message + '\'' +
                    ", i_time=" + i_time +
                    '}';
        }
    }
    // i_time(插入时间)，e_time(提醒时间），type（提醒类型），message（消息内容）
    private Logger logger = LoggerFactory.getLogger(BookingOperator.class);
    private static final String TAG = BookingOperator.class.getSimpleName();
    private String tableName = "booking";
    private SQLiteDatabase wdb;
    private SQLiteDatabase rdb;
    protected BookingOperator() {}
    protected BookingOperator(SQLiteOpenHelper helper) {
        wdb = helper.getWritableDatabase();
        rdb = helper.getReadableDatabase();
    }

    /**
     * 添加一条 预约 记录
     * @param time
     * @param type
     * @param message
     */
    public void booking(long time, String type, String message) {
        String sql = String.format("insert into %s('e_time', 'type', 'i_time', 'message') values ('%d', '%s', '%d', '%s')",
                tableName, time, type, System.currentTimeMillis(), message);
        logger.debug(TAG, sql);
        wdb.execSQL(sql);
        logger.debug(TAG, "insert success");
    }

    /**
     * 删除 time时的 type 预约记录
     * @param time
     * @param type
     */
    public void delete(long time, String type) {
        time = time - time % 1000;
        logger.debug(TAG, "delete from {} where e_time >= {} and e_time < {} and type = {}", tableName, time, time+1000, type);
        int i = wdb.delete(tableName, "e_time >= ? and e_time < ? and type = ?",
                new String[]{String.valueOf(time), String.valueOf(time + 1000), type});
        logger.debug(TAG, "delete count {}", i);
    }

    /**
     * 查询当前的type 预约记录
     * @param type
     * @return
     */
    public Booking selectNow(String type) {
        return select(System.currentTimeMillis(), type);
    }

    /**
     * 在time时是否存在type的记录
     * @param time
     * @param type
     * @return
     */
    public boolean exist(long time, String type) {
        time = time - time % 1000;
        String sql = "select exists( select 1 from booking where e_time>=? and e_time<? and type=? )";
        logger.debug(TAG, "{} p1={} p2={} p3={}", sql, time, time+1000, type);
        Cursor c = rdb.rawQuery(sql, new String[]{
                String.valueOf(time), String.valueOf(time + 1000), type
        });
        int rst = OperatorUtil.first(c, true, (cu) -> {
            return cu.getInt(0);
        });
        c.close();
        logger.debug(TAG, "exists rst {}", rst);
        return rst != 0;
    }

    /**
     * 删除time之前（不包括time）的所有type的记录
     * @param time
     * @param type
     * @return
     */
    public int deleteBefore(long time, String type) {
        time = time - time % 1000;
        logger.debug(TAG, "delete from {} where e_time<{} and type={}", tableName, time, type);
        int i = wdb.delete(tableName, "e_time<? and type=?",
                new String[]{String.valueOf(time), type});
        logger.debug(TAG, "delete count {}", i);
        return i;
    }

    /**
     * 查找time时的type记录
     * @param time
     * @param type
     * @return
     */
    public Booking select(long time, String type) {
        time = time - time % 1000;
        String sql = "select e_time,type,i_time,message from booking where e_time>=? and e_time<? and type=?";
        logger.debug(TAG, "{} p1={} p2={} p3={}", sql, time, time + 1000, type);
        Cursor c = rdb.rawQuery(sql, new String[]{
                        String.valueOf(time), String.valueOf(time + 1000), type
                    });
        Booking booking = OperatorUtil.first(c, true, (cu) -> {
            return new Booking(cu.getLong(0), cu.getString(1),
                    cu.getString(3), cu.getLong(2)
            );
        });
        c.close();
        logger.debug(TAG, "select success {}", booking);
        return booking;
    }
}
